package com.bulletelc.apollopre.module.main.center.orders.orderComment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.OrderItemCommentBean;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.utils.Base64Util;
import com.bulletelc.apollopre.utils.FileUtil;
import com.bulletelc.apollopre.utils.ImageUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

/**
 * Created by CX on 2018/2/2.
 */

public class FinishCommentActivity extends MVPBaseActivity<FinishCommentContract.View, FinishCommentContract.Presenter>
implements FinishCommentContract.View, View.OnClickListener, FinishCommentGridViewPicAdapter.onPicAddListener,
FinishCommentGridViewPicAdapter.onPicCancelListener, FoolBar.ClickCallback {

    // views
    private FoolBar flBar;
    private ListView listView;
    private CheckBox cbAnonymous;
    private Button btnSubmit;
    private ProgressBar pbLoad;

    // data
    private FinishCommentAdapter adapter;
    private List<OrderItemCommentBean> oicList;
    public static int imgPosition, itemPosition;
    private String orderId; // 大订单ID

    @Override
    public int getLayoutRes() {
        return R.layout.order_comment_list_activity;
    }

    @Override
    public void assignViews() {
        flBar = findViewById(R.id.flBar);
        flBar.setTitle(this.getResources().getString(R.string.order_comment));
        listView = findViewById(R.id.lvComment);
        cbAnonymous = findViewById(R.id.cbAnonymous);
        btnSubmit = findViewById(R.id.btnSubmit);
        pbLoad = findViewById(R.id.pbLoad);
    }

    @Override
    public void setListener() {
        flBar.setClickCallback(this);
        btnSubmit.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        oicList = new ArrayList<>();
        adapter = new FinishCommentAdapter(this, oicList);
        listView.setAdapter(adapter);
        Intent intent = getIntent();
        if (intent != null) {
            orderId = intent.getStringExtra(IntentCode.EXTRA_KEY_ORDER_ID);
            presenter.getOrderDetail(orderId);
        } else {
            Toast.makeText(this, "请求参数错误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onSuccessGetOrderDetail(List<OrderItemCommentBean> oicList) {
        if (oicList != null && oicList.size() > 0) {
            this.oicList.clear();
            this.oicList.addAll(oicList);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onFailGetOrderDetail(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorGetOrderDetail(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onSuccessPostComment() {
        Toast.makeText(this, "评论完成", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onFailPostComment(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorPostComment(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    protected FinishCommentContract.Presenter createPresenter() {
        return new FinishCommentPresenter();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && (PhotoPicker.REQUEST_CODE==requestCode || PhotoPreview.REQUEST_CODE==requestCode)) {
            List<String> picturePath = new ArrayList<>();
            if (data!=null) {
                picturePath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                //更新adapter
                ArrayList<HashMap<String,String>> gridPicPath = oicList.get(itemPosition).getImgPath();
                for (int i = 0; i < picturePath.size(); i++) {
                    HashMap<String,String> hashMap = new HashMap<>();
                    hashMap.put("content", picturePath.get(i));
                    gridPicPath.add(hashMap);
                }
                adapter.notifyDataSetChanged();
            }

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSubmit: //提交评论
                MyUtil.setProgressBar(pbLoad, true);
                submit();
                break;
        }
    }

    @Override
    public void click(int itemPos, int position) {
        this.imgPosition = position;
        this.imgPosition = itemPos;
    }

    @Override
    public void cancelClick(int position) {
        this.imgPosition = position;
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    /**
     * 获取是否匿名
     * @param isChecked
     * @return
     */
    private int isAnonymous(boolean isChecked) {
        return isChecked ? 1 : 0;
    }

    /**
     * 提交评论
     */
    private void submit() {
        boolean checked = cbAnonymous.isChecked();
        String json;
        JSONObject obj = new JSONObject();
        JSONArray arrSub = new JSONArray();
        for (int o = 0; o < oicList.size(); o++) {
            ArrayList<HashMap<String,String>> paths = oicList.get(o).getImgPath();
            String mark = oicList.get(o).getMark();
            String content = oicList.get(o).getContent();
            if ("0".equals(mark)) {
                Toast.makeText(this, "请评星级", Toast.LENGTH_SHORT).show();
                return;
            }
            if ("".equals(content)) {
                Toast.makeText(this, "请输入评论内容", Toast.LENGTH_SHORT).show();
                return;
            }
            JSONObject objSub = new JSONObject();
            JSONObject objImg = new JSONObject();
            JSONArray arrImg = new JSONArray();
            JSONObject objTmp = null;
            try {
                objSub.put("sales_order_id", orderId);
                objSub.put("sales_order_item_id", oicList.get(o).getOrderId());
                objSub.put("product_id", oicList.get(o).getGoodId());
                objSub.put("product_sku_id", oicList.get(o).getGoodSkuId());
                objSub.put("content", content);
                objSub.put("total_mark", mark);
                objSub.put("is_anonymous", isAnonymous(checked));
                if (paths != null && paths.size() > 0) {
                    for (int s = 0; s < paths.size(); s++) {
                        if (!paths.get(s).get("content").equals("")) {
                            // 图片压缩
                            String tmpPath = ImageUtil.saveBitmap(paths.get(s).get("content"), "tmpPic"+System.currentTimeMillis());
                            objTmp = new JSONObject();
                            String base64String = "data:image/" + FileUtil.getFileExtension(tmpPath) + ";base64," + Base64Util.fileToBase64String(tmpPath);
                            objTmp.put("base64_image", base64String);
                            arrImg.put(objTmp);
                            objTmp = null;
                        }
                    }
                }
                arrImg.put(objImg);
                objSub.put("images", arrImg);
                arrSub.put(objSub);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            obj.put("product_comment", arrSub);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        json = obj.toString();
        if (json != null) {
            presenter.postComment(json);
        } else {
            Toast.makeText(this, "提交参数有误", Toast.LENGTH_SHORT).show();
        }
    }

}
